package com.sduept.nwld.mobile.manager;

import org.springframework.beans.factory.annotation.Autowired;

import org.apache.commons.lang.StringUtils;

import com.sduept.core.ParamManager;
import org.springframework.stereotype.Service;

@Service
public class MobileUtil {

	@Autowired
	private ParamManager paramCache;
	
	public static final String NWLD_MOBILE_SQL_CHECK = "nwld_mobile_sql_check";// 移动端推送的消息类型
	
	/**
	 * sql注入检查，若开启注入检查，给定字符串中含有关键字，会抛出异常；不含关键字或者没开启检查，则不做处理。
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public String SQLInjectCheck(String str) throws Exception {
		int isCheck = Integer.parseInt(paramCache.get(NWLD_MOBILE_SQL_CHECK).getValue());//0:检查，1：不检查
		if(isCheck == 0){
			str =MobileUtil.keywordCheck(str);
		}
		return str;
	}
	
	/**
	 * 截去关键字并返回
	 * @param str
	 * @return
	 */
	public static String sqlConvert(String str) {
		if(StringUtils.isEmpty(str)){
			return str;
		}else{
			String strLow = str.toLowerCase();
			String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|" +  
					"char|declare|sitename|version|substr|db_name|user|net user|xp_cmdshell|;|or|+|,|like'|create|" +  
					"table|from|grant|use|group_concat|column_name|" +  
					"information_schema.columns|table_schema|union|where|order|by|" + 
					"add|all|alter|analyze|as|asc|asensitive|any|as|ascii|asensitive|at|autoextend_size|" + 
					"auto_increment|avg|avg_row_length|backup|begin|before|between|bigint|binary|binlog|bit|blob|block|bool|" + 
					"boolean|both|btree|by|byte|cache|call|cascade|cascaded|case|catalog_name|chain|change|changed|chanel|char|" + 
					"character|charset|check|checksum|cipher|class_origin|client|close|coalesce|code|collate|collation|column|columns|" +
					"column_format|column_name|comment|commit|committed|compact|completion|compressed|compression|concurrent|" +
					"condition|connection|consistent|constraint|constraint_catalog|constraint_name|constraint_schema|contains|" +
					"context|continue|convert|cpu|cross|cube|current|current_date|current_time|current_timestamp|current_user|" +
					"cursor|cursor_name|data|database|databases|datafile|date|datetime|day|day_hour|day_microsecond|day_minute|" +
					"day_second|deallocate|decimal|declare|default|default_auth|definer|delayed|delay_key_write|desc|describe|" +
					"des_key_file|deterministic|diagnostics|directory|disable|discard|disk|distinct|" +
					"chr|mid|master|truncate|char|declare|--|like|(|)|+|\"|=|//|/|／|#";//过滤掉的sql关键字，可以手动添加  
			String[] badStrs = badStr.split("\\|");
			for(int i = 0; i < badStrs.length; i++){
				if(strLow.indexOf(badStrs[i]) != -1){
					int startSt = strLow.indexOf(badStrs[i]);
					int endSt = strLow.indexOf(badStrs[i]) + badStrs[i].length();
					strLow = strLow.replace(badStrs[i], "");
					str = str.substring(0, startSt) + str.substring(endSt);
				}
			}
			return str;
		}
	}
	
	/**
	 * 关键字校验，所传字符串含有关键字：抛出异常；不含关键字：返回所传字符串。
	 * @param str
	 * @return
	 * @throws Exception 
	 */
	public static String keywordCheck(String str) throws Exception {
		if(StringUtils.isEmpty(str)){
			return str;
		}else{
			String strLow = str.toLowerCase();
			String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|" +  
				"char|declare|sitename|version|substr|db_name|user|net user|xp_cmdshell|;|or|+|,|like'|create|" +  
				"table|from|grant|use|group_concat|column_name|" +  
				"information_schema.columns|table_schema|union|where|order|by|" + 
				"add|all|alter|analyze|as|asc|asensitive|any|as|ascii|asensitive|at|autoextend_size|" + 
				"auto_increment|avg|avg_row_length|backup|begin|before|between|bigint|binary|binlog|bit|blob|block|bool|" + 
				"boolean|both|btree|by|byte|cache|call|cascade|cascaded|case|catalog_name|chain|change|changed|chanel|char|" + 
				"character|charset|check|checksum|cipher|class_origin|client|close|coalesce|code|collate|collation|column|columns|" +
				"column_format|column_name|comment|commit|committed|compact|completion|compressed|compression|concurrent|" +
				"condition|connection|consistent|constraint|constraint_catalog|constraint_name|constraint_schema|contains|" +
				"context|continue|convert|cpu|cross|cube|current|current_date|current_time|current_timestamp|current_user|" +
				"cursor|cursor_name|data|database|databases|datafile|date|datetime|day|day_hour|day_microsecond|day_minute|" +
				"day_second|deallocate|decimal|declare|default_auth|definer|delayed|delay_key_write|desc|describe|" +
				"des_key_file|deterministic|diagnostics|directory|disable|discard|disk|distinct|" +
				"chr|mid|master|truncate|char|declare|--|like|(|)|+|\"|=|//|/|／|#";//过滤掉的sql关键字，可以手动添加  
			String[] badStrs = badStr.split("\\|");
			for(int i = 0; i < badStrs.length; i++){
				if(strLow.indexOf(badStrs[i]) != -1){
					throw new Exception("所传参数不合法！");
				}
			}
			return str;
		}
	}
	
	/**
	 * 判断给定字符串中是否含有关键字，含有：返回true，不含：返回false。
	 * @param str
	 * @return
	 */
	public static boolean containsKeyword(String str) {
		if(StringUtils.isEmpty(str)){
			return false;
		}else{
			String strLow = str.toLowerCase();
			String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|" +  
				"char|declare|sitename|version|substr|db_name|user|net user|xp_cmdshell|;|or|+|,|like'|create|" +  
				"table|from|grant|use|group_concat|column_name|" +  
				"information_schema.columns|table_schema|union|where|order|by|" + 
				"add|all|alter|analyze|as|asc|asensitive|any|as|ascii|asensitive|at|autoextend_size|" + 
				"auto_increment|avg|avg_row_length|backup|begin|before|between|bigint|binary|binlog|bit|blob|block|bool|" + 
				"boolean|both|btree|by|byte|cache|call|cascade|cascaded|case|catalog_name|chain|change|changed|chanel|char|" + 
				"character|charset|check|checksum|cipher|class_origin|client|close|coalesce|code|collate|collation|column|columns|" +
				"column_format|column_name|comment|commit|committed|compact|completion|compressed|compression|concurrent|" +
				"condition|connection|consistent|constraint|constraint_catalog|constraint_name|constraint_schema|contains|" +
				"context|continue|convert|cpu|cross|cube|current|current_date|current_time|current_timestamp|current_user|" +
				"cursor|cursor_name|data|database|databases|datafile|date|datetime|day|day_hour|day_microsecond|day_minute|" +
				"day_second|deallocate|decimal|declare|default|default_auth|definer|delayed|delay_key_write|desc|describe|" +
				"des_key_file|deterministic|diagnostics|directory|disable|discard|disk|distinct|" +
				"chr|mid|master|truncate|char|declare|--|like|(|)|+|\"|=|//|/|／|#";//过滤掉的sql关键字，可以手动添加  
			String[] badStrs = badStr.split("\\|");
			for(int i = 0; i < badStrs.length; i++){
				if(strLow.indexOf(badStrs[i]) != -1){//含有
					return true;
				}
			}
			return false;
		}
	}
	
	/**
	 * 判断字符串是否全是0~9
	 * @param str
	 * @return 是：true，否：false
	 */
	public static boolean checkNum(String str){
		
		for(int i = 0; i < str.length(); i++){
			if(!Character.isDigit(str.charAt(i))){//不是0-9
				return false;
			}
		}
		return true;
	}
	
}
